#!/usr/bin/env python
# -*- coding:utf-8 -*-
import json

from flask import current_app
from flask import jsonify
from flask import request
from i_manager.background.models_sqlalchemy import Site
from . import site_api as app


@app.route('/start_crawl', methods=['GET'])
def start_crawl():
    site = request.args.get('site', '')
    try:
        if site:
            scheduler = current_app.config['scheduler']
            scheduler.start_one_site_tasks(site)
        else:
            raise Exception('no argument id')
    except Exception, e:
        return jsonify({'code': 500, 'status': False, 'data': e.message, 'count': 0})
    return jsonify({'code': 0, 'status': True, 'count': 1, 'data': ''})


@app.route('/stop_crawl', methods=['GET'])
def stop_crawl():
    site = request.args.get('site', '')
    try:
        if site:
            scheduler = current_app.config['scheduler']
            scheduler.stop_one_site_tasks(site)
        else:
            raise Exception('no argument id')
    except Exception, e:
        return jsonify({'code': 500, 'status': False, 'data': e.message, 'count': 0})
    return jsonify({'code': 0, 'status': True, 'count': 1, 'data': ''})


@app.route('/delete_site', methods=['GET'])
def delete_site():
    args = request.args
    session = current_app.config['Dsession']()
    try:
        if not session.query(Site).filter_by(id=int(args['id'])).count():
            raise Exception('no this site')
        session.query(Site).filter_by(id=int(args['id'])).delete()
        session.commit()
        return jsonify({'status': True, 'count': 0, 'data': {'id': args['id']}})
    except Exception, e:
        return jsonify({'status': False, 'data': e.message})
    finally:
        if session:
            session.close()


@app.route('/delete_cache', methods=['GET'])
def delete_cache():
    site = request.args.get('site', '')
    try:
        if site:
            scheduler = current_app.config['scheduler']
            scheduler.clear_one_site_cache(site)
        else:
            raise Exception('no argument id')
    except Exception, e:
        return jsonify({'code': 500, 'status': False, 'data': e.message, 'count': 0})
    return jsonify({'code': 0, 'status': True, 'count': 1, 'data': ''})
